const cacheStorageKey = 'minimal-pwa-3';
const cacheList = [
  "/",
  "index.html",
  "main.css",
  "apple-touch-icon.png"
]


self.addEventListener('install', e=>{
  e.waitUntil(
    caches.open(cacheStorageKey)
    .then(cache=>cache.addAll(cacheList))
    .then(()=>self.skipWaiting())
  );
});


self.addEventListener('fetch',e=>{
  e.respondWith(
    caches.match(e.request).then((response)=>{
      if(response != null){
        return response;
      }
      return fetch(e.request.url);
    })
  )
});


self.addEventListener('activate', e=>{
  e.waitUntil(
    caches.keys().then(cacheNames=>{
      return Promise.all(
        cacheNames.filter(cacheNames=>{
          return cacheNames !== cacheStorageKey
        }).map(cacheNames=>{
          return caches.delete(cacheNames)
        })
      )
    }).then(()=>{
      return self.clients.claim();
    })
  );
});


/* 消息推送 */
self.addEventListener('push', e => {
  // do something
});


/* 推送消息对话框点击事件 */
self.addEventListener('notificationclick', e => {
  // do something
});